package realQuestion.tri89;

import listNodePractice.ListNode;

import java.util.Optional;
import java.util.PriorityQueue;

public class Main1 {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length==0){
            return  null;
        }
        ListNode dumpy = new ListNode(-1);
        ListNode p=dumpy;
        PriorityQueue<ListNode> pq=   new PriorityQueue<>(lists.length,(a,b)->(a.val-b.val));
        for(ListNode head:lists){
            if(Optional.ofNullable(head).isPresent()){
                pq.add(head);
            }
        }
        while(!pq.isEmpty()){
            ListNode node=pq.poll();
            p.next=node;

            if(Optional.ofNullable(node.next).isPresent()){
                pq.add(node.next);
            }
            p=p.next;
        }
        return  dumpy.next;
    }
}
